package me.zhengjie.WcsReport;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.pojo.dto.BuzzerDto;
import me.zhengjie.pojo.dto.McuDto;
import me.zhengjie.pojo.vo.BuzzerVo;
import me.zhengjie.pojo.vo.McuVo;
import me.zhengjie.sqlservice.WcsAgvIdService;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

@Service
@Slf4j
@RequiredArgsConstructor
public class BuzzerServiceImpl implements BuzzerService{
    private final WcsAgvIdService wcsAgvIdService;
    private final RestTemplate restTemplate;

    @Override
    public BuzzerVo buzzerSend(BuzzerDto buzzerDto,String ip) {
        // 获取 IP 地址

        // 设置请求头
        HttpHeaders httpHeaders = new HttpHeaders();
        httpHeaders.set("cmd", "sendAlarm");

        // 创建请求实体
        HttpEntity<BuzzerDto> buzzerDtoHttpEntity = new HttpEntity<>(buzzerDto, httpHeaders);

        // 日志记录请求信息
        log.info("请求地址：{}, 参数：{}", ip, buzzerDto);

        try {
            // 发送请求并获取响应
            ResponseEntity<byte[]> responseEntity = restTemplate.exchange(
                    ip,
                    HttpMethod.POST,
                    buzzerDtoHttpEntity,
                    byte[].class
            );

            // 获取响应体字节数组
            byte[] responseBody = responseEntity.getBody();
            if (responseBody == null) {
                throw new RuntimeException("Response body is null");
            }

            // 将字节数组转换为字符串
            String responseString = new String(responseBody, StandardCharsets.UTF_8);

            // 将字符串解析为 BuzzerVo 对象
            ObjectMapper objectMapper = new ObjectMapper();
            BuzzerVo buzzerVo = objectMapper.readValue(responseString, BuzzerVo.class);

            // 日志记录响应结果
            log.info("响应结果: {}", buzzerVo);

            return buzzerVo;
        } catch (Exception e) {
            // 处理异常
            log.error("Error occurred while sending buzzer request", e);
            return null;
        }
    }

    @Override
    public McuVo mcuSend(McuDto mcuDto,String ip) {
        log.info("单片机请求参数:{},ip：{}",mcuDto,ip);
        McuVo mcuVo = restTemplate.postForObject(ip, mcuDto, McuVo.class);
        log.info("返回结果：{}",mcuVo);
        return mcuVo;
    }
}
